<template>
  <q-tabs v-model="currentServeId" active-class="service-list-active-cls text-weight-bold text-white" breakpoint="0"
    class="col" indicator-color="transparent" @update:model-value="clickServe">
    <q-tab v-for="serve in serviceList" :key="serve.id" :name="serve.id" :ripple="{ color: 'primary' }"
      class="service-list-item flex flex-center q-pa-md text-subtitle1 cursor-pointer full-height rounded-borders">
      <qx-tooltip class="text-capitalize">{{ serve[toI18nName('serviceNameZhCn')] }}</qx-tooltip>
    </q-tab>
  </q-tabs>

  <q-inner-loading :showing="loading" class="service-list-loading no-margin">
    <q-spinner-ios color="transparent" size="3rem" />
  </q-inner-loading>
</template>

<script setup>
import { i18n, toI18nName } from 'boot/i18n'
import { createDialog } from 'src/utils/utils'
import { userStores } from 'stores/user-stores'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = userStores()
const loading = ref(false)
const currentServeId = ref('')

const serviceList = computed(() => userStore.serviceList)

watch(() => userStore.breadcrumbs?.id, serveId => currentServeId.value = serveId, { immediate: true })
const initMenus = (serve = {}, init) => {
  if (!serve.id) return
  loading.value = true
  userStore.GetMenus(serve.id, router).then(async menu => {
    if (init) return (loading.value = false)
    if (menu.LMenus && menu.LMenus.length) await router.replace(menu.LMenus[0].path)
    else {
      const msg = `${i18n.t('Misc.MenuAccess', [serve[toI18nName('serviceNameZhCn')]])}`
      createDialog({ msg }, () => { }, () => { })
      loading.value = false
      return
    }
    loading.value = false
    await nextTick(() => userStore.SET_BREADCRUMBS(serve))
  }).catch(() => (loading.value = false))
}

const clickServe = serveId => {
  if (serveId === (userStore.breadcrumbs || {}).id) return
  currentServeId.value = (userStore.breadcrumbs || {}).id
  const serve = serviceList.value.find(el => el.id === serveId) || {}
  initMenus(serve)
}
onMounted(() => initMenus(userStore.breadcrumbs || {}, true))
</script>